# sentiment_utils.py
import math
from django.db.models import Q, Count, Avg, FloatField
from django.db.models.functions import Cast
from .models import TouristAttraction, SentimentComment


def calculate_comprehensive_sentiment_score(attraction):
    """计算综合情感得分 - 安全版本"""
    try:
        # 安全获取字段值
        review_count = getattr(attraction, 'review_count', 0) or 0
        positive_count = getattr(attraction, 'positive_count', 0) or 0
        negative_count = getattr(attraction, 'negative_count', 0) or 0

        if review_count == 0:
            return 0

        # 计算基础情感分数
        base_score = (positive_count - negative_count) / review_count

        # 考虑其他因素（评分、热度等）
        rating = getattr(attraction, 'avg_rating', 0) or 0
        view_count = getattr(attraction, 'view_count', 0) or 0

        # 综合得分公式（可根据需求调整权重）
        comprehensive_score = (
                base_score * 0.6 +  # 情感基础分权重
                (rating / 5) * 0.3 +  # 评分权重
                (min(view_count, 10000) / 10000) * 0.1  # 热度权重
        )

        return round(comprehensive_score, 3)

    except Exception as e:
        print(f"Error in calculate_comprehensive_sentiment_score: {e}")
        return 0


def calculate_comment_quality(attraction):
    """计算评论质量得分"""
    comments = SentimentComment.objects.filter(attraction=attraction, is_active=True)

    if not comments.exists():
        return 0

    # 计算平均评论长度
    avg_length = sum(len(comment.content) for comment in comments) / comments.count()
    length_score = min(avg_length / 50, 1.0)  # 假设50字为满分

    # 计算有评分的评论比例
    rated_comments = comments.exclude(rating__isnull=True)
    rating_ratio = rated_comments.count() / comments.count()

    return (length_score + rating_ratio) / 2


def get_sentiment_ranking(attraction):
    """获取情感排名信息 - 安全版本"""
    try:
        from .models import TouristAttraction

        # 获取所有已发布的景点
        all_attractions = TouristAttraction.objects.filter(status='published')

        # 计算每个景点的综合得分
        ranked_attractions = []
        for attr in all_attractions:
            score = calculate_comprehensive_sentiment_score(attr) or 0
            ranked_attractions.append({
                'attraction': attr,
                'score': score
            })

        # 按得分排序
        ranked_attractions.sort(key=lambda x: x['score'], reverse=True)

        # 找到当前景点的排名
        current_rank = None
        for i, item in enumerate(ranked_attractions, 1):
            if item['attraction'].id == attraction.id:
                current_rank = i
                break

        return {
            'current_rank': current_rank or len(ranked_attractions) + 1,
            'total_ranked': len(ranked_attractions),
            'top_attractions': ranked_attractions[:5]  # 前5名
        }

    except Exception as e:
        print(f"Error in get_sentiment_ranking: {e}")
        return {
            'current_rank': None,
            'total_ranked': 0,
            'top_attractions': []
        }


def get_positive_ratio(attraction):
    """计算积极评论比例"""
    if attraction.review_count == 0:
        return 0
    return (attraction.positive_count / attraction.review_count) * 100